import Vue from 'vue';
import Vuex from 'vuex';
import event from './event';
import compList from './compList';
import { setToken, removeToken } from '@/utils/auth';
import { validatenull } from '@/utils/validate';
import { loginByUsername, getSelectAllList, logout } from '@/api/login';
import { setStore, getStore, clearStore } from '@/utils/store';
import { Message } from 'element-ui';
import md5 from 'js-md5';
Vue.use(Vuex);
const store = new Vuex.Store({
	state: {
		token: getStore({ name: 'dvp-token' }) || '',
		tenantId: getStore({ name: 'dvp-tenantId' }) || '',
		siteId: getStore({ name: 'dvp-siteId' }) || '',
		userInfo: getStore({ name: 'dvp-userInfo' }) || [],
		globalVariable: {}, // 全局变量
		globalHeader: {},
		compsList: [], // 画布内所有组件
		areaData: {
			// 选中区域包含的组件以及区域位移信息
			style: {
				top: 0,
				left: 0,
				width: 0,
				height: 0
			},
			components: []
		},
		activeComps: [] // 选中组件信息集合
	},
	getters: {
		// 接数组件集合
		rceiveDataComps: state => {
			return state.compsList.filter(comp => comp.isReceiveDataComp);
		},
		activeCompsIndex: state => {
			return state.activeComps.map(comp => comp.index); // 选中组件基础信息集合
		},
		avatar: state => {
			return state.userInfo.avatar;
		},
		userId: state => {
			return state.userInfo.user_id;
		},
		userName: state => {
			return state.userInfo.user_name;
		}
	},
	mutations: {
		// 设置画布内组件 data:传入的组件信息数组
		setCanvasCompsList(state, data) {
			if (state.compsList.length > 0) {
				let findCompList = data.filter(d => {
					let comps = state.compsList.map(comp => comp.index);
					return !comps.includes(d.index);
				});
				if (findCompList && findCompList.length > 0) {
					findCompList.map(comp => {
						state.compsList.unshift(comp);
					});
				}
			} else {
				state.compsList = data;
			}
		},
		// 根据组件id清除画布内组件
		clearCanvasCompList(state, compIds) {
			if (compIds && compIds.length > 0) {
				state.compsList = state.compsList.filter(comp => {
					return !compIds.includes(comp.index);
				});
			}
		},
		clearAllCompsList(state) {
			state.compsList = [];
			state.activeComps = [];
		},
		setHistroyData(state, data) {
			state.compsList = data;
		},
		// 设置圈选组件数据
		setAreaData(state, data) {
			state.areaData = data;
			if (data.isGroup) {
				state.activeComps = data.activeComps;
			} else {
				if (state.areaData.components.length > 0) {
					state.activeComps = state.areaData.components;
				}
			}
		},
		setActiveComps(state, item) {
			let { index, isKeysCtrl } = item;
			if (!isKeysCtrl) {
				state.activeComps = [];
			}
			let find = state.activeComps.find(comp => comp.index == index);
			if (!find) {
				state.activeComps.push({
					...item,
					isLock: item.isLock || false
				});
			}
		},
		clearActiveComps(state) {
			state.activeComps = [];
			let activeDom = document.querySelectorAll('.groupArea .avue-draggable--active');
			activeDom.forEach(dom => {
				dom.classList.remove('avue-draggable--active');
				let lineDom = dom.querySelectorAll('.avue-draggable__wrapper .avue-draggable__line');
				let rangeDom = dom.querySelectorAll('.avue-draggable__wrapper .avue-draggable__range');

				lineDom.forEach(lDom => {
					lDom.style.display = 'none';
				});
				rangeDom.forEach(rDom => {
					rDom.style.display = 'none';
				});
			});
		},
		setGlobalHeader(state, data) {
			state.globalHeader = data;
		},
		setGlobalVariable(state, data) {
			state.globalVariable = data;
		},
		SET_TOKEN: (state, token) => {
			setToken(token);
			state.token = token;
			setStore({ name: 'dvp-token', content: state.token });
		},
		SET_TENANT_ID: (state, tenantId) => {
			state.tenantId = tenantId;
			setStore({ name: 'dvp-tenantId', content: state.tenantId });
		},
		SET_SITE_ID: (state, siteId) => {
			state.siteId = siteId;
			setStore({ name: 'dvp-siteId', content: state.siteId });
		},
		SET_USER_INFO: (state, userInfo) => {
			if (validatenull(userInfo.avatar)) {
				userInfo.avatar = '/img/bg/img-logo.png';
			}
			state.userInfo = userInfo;
			setStore({ name: 'dvp-userInfo', content: state.userInfo });
		}
	},
	actions: {
		SetCanvasCompsListAsync({ commit }, data) {
			commit('setCanvasCompsList', data);
		},
		SetGlobalHeaderAsync({ commit }, data) {
			commit('setGlobalHeader', data);
		},
		SetGlobalVariableAsync({ commit }, data) {
			commit('setGlobalVariable', data);
		},
		//根据用户名登录
		LoginByUsername({ commit }, userInfo) {
			return new Promise((resolve, reject) => {
				loginByUsername(userInfo.tenantId, userInfo.username, md5(userInfo.password), 'account', '', '')
					.then(res => {
						const data = res.data;
						if (data.error_description) {
							Message({
								message: data.error_description,
								type: 'error'
							});
						} else {
							commit('SET_TOKEN', data.access_token);
							commit('SET_TENANT_ID', data.tenant_id);
							commit('SET_USER_INFO', data);
							getSelectAllList()
								.then(res => {
									if (res.status === 200) {
										let data = res.data.data;
										if (data && data.length > 0) {
											commit('SET_SITE_ID', data[0].id);
										}
									}
								})
								.catch(() => {});
						}
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		},
		// 登出
		LogOut({ commit }) {
			return new Promise((resolve, reject) => {
				logout()
					.then(() => {
						commit('SET_TOKEN', '');
						removeToken();
						clearStore({ type: 'session' });
						clearStore();
						resolve();
					})
					.catch(error => {
						reject(error);
					});
			});
		}
	},
	modules: {
		event,
		compList
	}
});

export default store;
